1 Getting started with C++
As computers have grown more powerful, computer programs have become larger and more complex. In response to these conditions, computer languages have evolved so that it's easier to manage the programming process. The C language incorporated features such as control structures and functions to better control the flow of a program and to enable a more structured, modular approach. To these tools C++ adds support for object-oriented programming and generic programming. This enables even more modularity and facilitates the creation of reusable code, which saves time and increases program reliability.
The popularity of C++ has resulted in a large of number of implementations for many computing platforms; The C++ ISO standards(C++98/03 and c++11) provide a basis for keeping these many implementations mutually compatible. The standards establishes the features the lanugage should have, the behavior the lanugage should display, and a standard language of functions, classes, and templates. The standards supports the goal of a portable language across different computing platforms and different implementations of the language.
To create a C++ program, you create one or more source files containing the program as expressed in the C++ language. These are text files that must be compiled and linked to produce the machine-language files that constitute executable programs. These tasks are often accomplished in an IDE that provides a text editor for creating the source files, a compiler and a linker for producing executable files, and other resources, such as project management and debugging capabilities. But the same tasks can also be performed in a command-line environment by invoking the appropriate tools individually.
图片描述(最多50字)
2 Simple Variables
int num;
num = 5;
These statements tell the program that it is storing an integer and that the name num represents the integer's value, 5 in this case, the program locates a chunk of memory large enough to hold an integer, notes the location, and copies the value 5 into the location. You then can use num later in your program to access that memory location. These statements don't tell you where in memory the value is stored, but the program does keep track of that information, too. Indeed, you can use the & operator to retrieve num's address in memory. You'll learn about that operator when you investigate a second strategy for indentifying data-using pointers.
3 The char type: characters and small integers
Characters are represented by their numeric codes. The I/O system determines whether a code is interpreted as a character or as a number.
char ch;
cin >>ch; // input a letter M
cout <<ch;
On input, cin converts the keystroke input M to the value 77. On output, cout converts the value 77 to the displayed character M.
From smallest to largest, the integer types are bool, char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, and, with C++11, long long, and unsigned long long. There is also a wchar_t type whose placement in this sequence of size depends on the implementation.
4 Arrays
You can use the initialization from only when defining the array. You cannot use it later, and you cannot assign one array wholesale to another.
However, you can use subscripts and assign values to the elements of any array individually.
When initializing an array, you can provide fewer values than array elements. so, it's easy to initialize all the elements of an array to zero:
long totals[111] = {0};
The STL provides an alternative to arrays called the vector template class, and C++11 adds an array template class. These alternatives are more sophisticated and flexible than the built-in array composite type.
5 String
A string is a series of characters stored in consecutive bytes of memory. C++ has two ways of dealing with strings. The first, taken from C and often called a C-style string, then, an alternative method based on a string class library.
C-style strings: a arrays of chars, the last character of every strings is the null character,written \0.
图片描述(最多50字)
char bird[11] = "cheeps"; // the \0 is understood
char fish[] = "bubbles"; //let the compiler count
char *str = "const string"; //the r-value is a const string, whcih is a literal constant
The string class definition hides the array nature of a string and lets you treat a string much like an ordinary variable.
C-style strings use functions library to process string with header file
The string class, is more convenient and safe than using an array. For example, you can't simply assign one array to another, but you can assign one string object to another.
The string class simplifies combining strings. You can use the + operator to add two string objects together and the += operator to take on a string to the end of an existing string object. (C-style string use strcat() to combine two strings)
#include <iostream> #include <string> // make string class available #include <cstring> // C-style string library int main() { using namespace std; char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; // assignment for string objects and character arrays str1 = str2; // copy str2 to str1 strcpy(charr1, charr2); // copy charr2 to charr1 // appending for string objects and character arrays str1 += " paste"; // add paste to end of str1 strcat(charr1, " juice"); // add juice to end of charr1 // finding the length of a string object and a C-style string int len1 = str1.size(); // obtain length of str1 int len2 = strlen(charr1); // obtain length of charr1 cout << "The string " << str1 << " contains " << len1 << " characters.\n"; cout << "The string " << charr1 << " contains " << len2 << " characters.\n"; cin.get(); return 0; }
output:
The string panther paste contains 13 characters.
The string jaguar juice contains 12 characters.
6 Unions
A union can hold a single value, but it can be of a variety of types, with the member name indicating which mode is being used.
A union is a data format that can hold different data types but only one type at a time.
union one4all
{
int int_val;
long long_val;
double double_val;
};
one4all pail;
pail.int_val = 15; // store an int
cout << pail.int_val;
pail.double_val = 1.38; // store a double, int value is lost
cout << pail.double_val;
7 Enumerations
The C++ enum facility provides an alternative to const for creating symbolic constants. It also lets you define new types but in a fairly restricted fashion.
enum spectrum{red, orange, yellow, green, blue, violent, indgo, ultraviolet};
It establishes red, orange, yellow, and so on, as symbolic constants for the integer values 0-7. These constants are called enumerators.
spectrum band;
band = blue; //valid
band = 22; //invalid
int color = blue; //valid, spctrum type promoted to int
8 Logical operator
By using C++'s logical operators(&&,||,and !), you can combine or modify relational expressions to construct more elaborate tests.
9 The function
C++ provides many new function features that separate C++ from its C heritage. The new feature include inline functions, by-reference variable passing, default argument values, function overloading(polymorphism), and template functions.
The function header describe the interface bewteen called function and calling function: how many and what kinds of values to pass to the function and what sort of return type, if any, to get from it.
The main() function header describes the interface between program and the operating system.
The function call causes the program to pass the function arguments to the function and to transfer program execution to the function code. A return statement sends a value from a called function back to the called function, also the type of return value must be consistent with the return type of called function.
The augument is the value let calling function assign to the parameter of the called function. By default, C++ functions pass arguments by value. This means that the formal parameters in the function definition are new variables that are initialized to the values provided by the function call. Thus, C++ functions protect the integrity of the original data by working with copies.
C++ treats an array name argument as the address of the first element of the array. Techinically, this is still passing by value because the pointer is a copy of the original address, but the function uses the pointer to access the contents of the original array. When you declare formal parameters for a function, the following two declarations are equivalent:
typeName arr[];
typeName * arr;
The name of a C++ function acts as the address of the function. By using a function argument that is a pointer to a function, you can pass to a function the name of a second function that you want the first function to evoke.
Inline function, instead of having the program jump to a separate section of code to execute the function, the compiler replaces the function call with the corresponding code inline. An inline facility should be used only when the function is short.
A reference variable is a kind of disguised pointer that lets you create an alias(that is, a second name) for a variable. Reference variables are primarily used as arguments to functions that process structrues and class objects.
10 Storage duration, scope, linkage and namespaces
C++ offers many choices for storing data in memory. You have choices for how long data remains in memory(storage duration) and choices for which parts of a program have access to data(scope and linkage). and you can allocate memory dynamically by using new, the C++ namespace facility provides additional control over access. Larger programs typically consist of several source code files that may share some data in common.
Automatic variables are variables that are defined within a block, such as a function body or block within the body, they exist and are known only while the program executes statements in the block that contains the definition.
10.1 The one definition rule
If you use an external variable in several files, only one file can contain a definition for that variable. But every other file using the variable needs to declare that variable using the keyword exter.
double up ; //outer of function, definition, up is 0
extern int cats = 20; //definition because of initialization ,extern can be omit
extern int dogs; dogs defined elsewhere
10.2 Global vs local variables
I Automatic(local) variable hides a global variable of the same name in the block of a function;
II Using scope-resolution operator(::) for using the global variable in block of function to avoid be hided by local variable which has the same name.
11 Objects and classes
OOP emphasizes how a program represents data. The first step toward solving a programming problem by using the OOP approach is to describe the data in terms of its interface with the program, specifying how the data is used. Next, you need to design a class that implements interface. Typically, private data members store the information whereas public member functions, also called methods, provide the only access to the data. The class combines data and methods into one unit, and the private aspect accomplishes data hiding.
Usually, you separate a class declaration into two parts, typically kept in separate files. The class declaration proper goes into a header file, with the methods represented by function prototypes. The source code that defines the member functions goes into a methods file. This approach separates the description of the interface from the details of the implementation. In principle, you need to know only the public class interface to use the class.
12 this pointer
this pointer is a implicit parameter of a member function, this points to the object on which the function is invoked. It is a pointer to the class type. In a const member function the pointer is a pointer to const.
以下三条语句的作用是相同的:
void Point::setx(double inputx)
{
x=inputx;
this->x = inputx;
(*this).x = inputx;
}
对于CShape类:
class CShape
{
...
public:
void setcolor(int color) { m_color = color; }
};
被编译器编译后,其实是:
class CShape
{
...
public:
void setcolor(int color, (CShape*)this) { this->m_color = color; }
};
13 Multifiles and Namespace
C++ encourages the use of multiple files in developing programs. An effective organizational strategy is to use a header file to define use types and provide function prototypes for functions to manipulate the user types. You should use a separate source code file for the function definitions. Together, the header file and the source file define and implement the user-defined type and how it can be used. Then, main() and other functions using those functions can go into a third file.
Some things commonly found in header files:
1 Function prototypes declarations;
2 Symbolic constants defined using #define or const;
3 Structure declarations
4 Extern variables declarations;
5 Class declarations
6 Template declarations;
7 Inline functions;
It's okay to put structure declarations in a header file because they don't create variables; they just tell the compiler how to create a structure variable when you declare one in a source code file. Simlilarly, template declarations aren't code to be compiled; they are instructions to the compiler on how to generate function definitions to match function calls found in the source code. Data declared const and inline functions have special linkage properties that allow them to be placed in header files without causing problems.
Namespaces let you define named regions in which you can declare identifiers. The intent is to reduce name conflicts, particularyly in arge programs that use code from several vendors. You can make available idntifiers in a namespace by using the scope-resolution operator. by a using declaration, or by using a using directive.
-End-
本页共150段,14114个字符,14374 Byte(字节)